package com.zzyl.nursing.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.ai.AiInvoker;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 健康评估Service业务层处理
 * 
 * @author zhx
 * @date 2025-05-20
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AiInvoker aiInvoker;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto dto)
    {
        //校验参数
        if (StringUtils.isBlank(dto.getElderName()) || "null".equals(dto.getElderName())){
            throw new BaseException("姓名参数非法");
        }

        if (StringUtils.isBlank(dto.getIdCard()) || "null".equals(dto.getIdCard())){
            throw new BaseException("身份证号参数非法");
        }
        if (StringUtils.isBlank(dto.getPhysicalExamInstitution()) || "null".equals(dto.getPhysicalExamInstitution())){
            throw new BaseException("体检机构参数非法");
        }
        if (StringUtils.isBlank(dto.getPhysicalReportUrl()) || "null".equals(dto.getPhysicalReportUrl())){
            throw new BaseException("体检报告URL参数非法");
        }

        //从Redis中读取体检报告PDF内容
        String pdfText =(String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_ASSESSMENT_TEXT_KEY,dto.getIdCard());
        if (StringUtils.isBlank(pdfText)){
            throw new BaseException("未上传体检报告PDF文件");
        }

        //从resources下读取prompt.txt中模版内容
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("prompt.txt");
        String template = IoUtil.read(inputStream, StandardCharsets.UTF_8);

        //组织prompt提示词
        String prompt = template.replace("prompt", pdfText);

        //调用百度千帆大模型单轮对话api接口,获取JSON结果
        String resultJSON = aiInvoker.invokeQianFanChat(prompt);
        if (StringUtils.isBlank(resultJSON)){
            throw new BaseException("调用千帆大模型接口失败");
        }

        //解析JSON字符串为healthReportVo对象
        HealthReportVo healthReportVo = JSON.parseObject(resultJSON, HealthReportVo.class);

        //新增健康评估表数据
        HealthAssessment assessment = new HealthAssessment();
        assessment.setElderName(dto.getElderName()); //老人姓名
        assessment.setIdCard(dto.getIdCard()); //身份证号
        assessment.setPhysicalExamInstitution(dto.getPhysicalExamInstitution()); //体检机构
        assessment.setPhysicalReportUrl(dto.getPhysicalReportUrl()); //体检报告URL连接
        assessment.setBirthDate(IdcardUtil.getBirthDate(dto.getIdCard()).toLocalDateTime()); //出生日期
        assessment.setAge(IdcardUtil.getAgeByIdCard(dto.getIdCard())); //年龄
        assessment.setGender(IdcardUtil.getGenderByIdCard(dto.getIdCard())); //性别
        double healthScore = healthReportVo.getHealthAssessment().getHealthIndex(); //健康评分(来自ai结果)
        assessment.setHealthScore(String.valueOf(healthScore));
        assessment.setTotalCheckDate(healthReportVo.getTotalCheckDate()); //总检日期(来自ai结果)
        assessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel()); //危险等级(来自ai结果)
        assessment.setReportSummary(healthReportVo.getSummarize()); //报告总结(来自ai结果)
        assessment.setDiseaseRisk(JSON.toJSONString(healthReportVo.getRiskDistribution())); //疾病风险-JSON格式(来自ai结果)
        assessment.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData())); //异常分析-JSON格式(来自ai结果)
        assessment.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore())); //8大健康系统分值-JSON格式(来自ai结果)
        assessment.setSuggestionForAdmission(healthScore>=60?0:1); //是否建议入住(0:建议 ,1:不建议)
        assessment.setNursingLevelName(getNursingLevelName(healthScore)); //推荐的护理等级
        assessment.setAdmissionStatus(1);//入住情况(0-已入住,1-未入住)
        assessment.setAssessmentTime(LocalDateTime.now()); //评估时间
        boolean result = this.save(assessment);
        if (!result){
            throw new BaseException("新增健康评估数据失败");
        }

        //从Redis中删除体检报告内容
        redisTemplate.opsForHash().delete(CacheConstants.HEALTH_ASSESSMENT_TEXT_KEY,dto.getIdCard());

        //返回表的主键id值
        return assessment.getId();
    }

    /**
     * 根据健康评分获取建议的护理等级
     * @param healthScore
     * @return
     */
    private String getNursingLevelName(double healthScore){
        String levelName = "不建议入住";
        if (healthScore<0 || healthScore>100){
            throw new BaseException("健康评分分值区间非法");
        }
        if (healthScore>=90){
            levelName = "三级护理";
        } else if (healthScore >= 80) {
            levelName = "二级护理";
        } else if (healthScore >= 70) {
            levelName = "一级护理";
        } else if (healthScore >= 60) {
            levelName = "特级护理";
        }
        return levelName;
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
}
